<template>
  <div class="interfaceImage">
    <DFPageList ref="dfPageListRef" :page-options="pageOptions">
      <template #imgUrl>
        <n-upload
          :default-file-list="previewFileList"
          :max="1"
          list-type="image-card"
          :custom-request="customRequest"
          accept=".png,.jpg,.jpeg,.pdf"
          @remove="handleRemove"
        />
      </template>
    </DFPageList>
  </div>
</template>

<script lang="ts" setup name="InterfaceImage">
  import lang from './lang';
  import {
    addInterfaceImage,
    delInterfaceImage,
    pageInterfaceImage,
    updateInterfaceImage,
  } from '@/api/gather/interfaceImage';
  import { uploadInterface } from '@/api/common';
  import { useMixins } from '@/hooks/useMixins';
  // import { infoParamConfig } from '@/api/system/paramConfig';
  import { storage } from '@/utils/Storage';

  const { loadLangFn } = useMixins();

  const dfPageListRef: any = ref(null);

  loadLangFn(lang);

  const previewFileList = ref([]);
  const pictureUrl = ref('');

  // function handlePreview(_file) {}
  function handleRemove(file) {
    console.log('file', file);
    previewFileList.value = [];

    if (dfPageListRef && dfPageListRef.value && dfPageListRef.value.setFieldsValueFn) {
      dfPageListRef.value.setFieldsValueFn({
        imgUrl: '',
      });
    }
  }

  async function customRequest({ file, onFinish, onError }) {
    const form = new FormData();

    form.append('file', file.file as string | Blob);

    const res = await uploadInterface(form);

    const { code, data } = res;

    if (code === 200) {
      onFinish();

      previewFileList.value.push({
        status: 'finished',
        url: data.url,
      });

      if (dfPageListRef && dfPageListRef.value && dfPageListRef.value.setFieldsValueFn) {
        dfPageListRef.value.setFieldsValueFn({
          imgUrl:
            trimSamePart(
              previewFileList.value.map((item) => item.url).join(','),
              pictureUrl.value
            ) || '',
        });
      }

      // console.log(previewFileList.value)
    } else {
      onError();
    }

    // console.log(res);
  }

  async function initDictData() {
    // const res = await Promise.all([infoParamConfig({ configCode: 'pictureUrl' })]);
    // const [list1] = res;
    // pictureUrl.value = list1.data?.configValue || `http://${storage.get('host')}:3000/file/`;

    pictureUrl.value = `http://${storage.get('host')}:3000/file/`;
  }

  initDictData();

  const pageOptions = {
    searchForm: {
      formSchemas: [
        {
          label: 'imgName',
        },
        {
          label: 'imgCode',
        },
      ],
    },
    table: {
      columns: [
        {
          width: 120,
          label: 'imgName',
        },
        {
          width: 120,
          label: 'imgCode',
        },
        {
          width: 160,
          label: 'imgUrl',
          render: (row) => {
            return h('span', {
              innerText: row.imgUrl ? row.imgUrl : '-',
            });
          },
        },
        {
          width: 100,
          label: 'imgUrlPic',
          render: (row) => {
            return h('img', {
              class:'imgUrlPic',
              src: row.imgUrl ? `${pictureUrl.value}${row.imgUrl}` : null,
            });
          },
        },
        {
          width: 120,
          label: 'remark',
          common: true,
        },
      ],
      action: {
        columns: [
          // {
          //   label: 'check',
          // },
          {
            label: 'edit',
          },
          {
            label: 'delete',
          },
        ],
      },
      operaColumn: [
        {
          label: 'add',
        },
      ],
      requestFn: pageInterfaceImage,
      delRequestFn: delInterfaceImage,
    },
    modalFormDialog: {
      formSchemas: [
        {
          label: 'imgName',
          required: true,
          giProps: { span: 4 },
          span: 3,
        },
        {
          label: 'imgCode',
          editDialogDisabled: true,
          required: true,
          giProps: { span: 4 },
          span: 3,
        },
        {
          label: 'imgUrl',
          slot: 'imgUrl',
          required: true,
          giProps: { span: 4 },
          span: 3,
        },
        {
          label: 'remark',
          common: true,
          type: 'textarea',
          giProps: { span: 4 },
          span: 3,
        },
      ],
      cols: 2,
      addDataFn: addInterfaceImage,
      updateDataFn: updateInterfaceImage,
      afterDialogSubmitFn: initDictData,
      setDialogDataFn: async (data, type) => {
        previewFileList.value = [];
        if (type === 'add') {
          const newData: any = {};
          return newData;
        }

        if (data && data.imgUrl)
          previewFileList.value = data.imgUrl
            .split(',')
            .map((item) => ({ url: `${pictureUrl.value}${item}`, status: 'finished' }));

        return data;
      },
      setDialogSubmitDataFn: (data) => {
        data.imgUrl =
          trimSamePart(previewFileList.value.map((item) => item.url).join(','), pictureUrl.value) ||
          '';
        return data;
      },
    },
  };

  function trimSamePart(str1, str2) {
    let index = 0;
    while (
      index < str1.length &&
      index < str2.length &&
      str1.charAt(index) === str2.charAt(index)
    ) {
      index++;
    }
    return str1.slice(index);
  }
</script>

<style lang="less" scoped>
.interfaceImage{
  :deep(.imgUrlPic){
    width: 100%;
    height: 50px;
    object-fit: fill;
  }
}
</style>
